package org.jiamandan.com.strategy;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jiamandan.com.dto.ZDBasicDto;
import org.jiamandan.com.strategy.enums.ZDEventTagEnum;
import org.jiamandan.com.strategy.impl.tram.IZDListenerService;
import org.jiamandan.com.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version Revision 1.0.1
 * @版权：版权所有 (c) 2021
 * @author:Jmd

 * @see:
 * @创建日期：2022-12-01 10:52
 * @功能说明：
 * @begin
 * @修改记录:
 * @修改后版本 修改人        修改内容
 * @2022-12-01 10:52	         Jmd        	创建
 * @end
 */
@Service
@Slf4j
public class ZDListenerContextService {

    @Autowired
    private final Map<String, IZDListenerService> strategyMap = new ConcurrentHashMap<>();

    public ZDListenerContextService(Map<String, IZDListenerService> strategyMap) {
        this.strategyMap.clear();
        strategyMap.forEach((k, v) -> this.strategyMap.put(k, v));
    }

    public void execute(ZDBasicDto dto, Channel client) throws Exception {
        //先移除右边的补零，如果还是4位长度，则开始高低位互换
//        log.info("开始移除右边的补零前命令：" + dto.getCmd());
//        String cmd = CommonUtil.removeZero(dto.getCmd(), false);
//        log.info("移除右边的补零移除后命令：" + cmd);
//        if (cmd.length() == 4) {
//            String orgCmd = CommonUtil.removeZero(CommonUtil.reverseHex(dto.getCmd()), true);
        String cmd = "0";
        if(dto.getStartPrefix().equals("68")){
            cmd = Integer.parseInt(CommonUtil.reverseHex(dto.getCmd()), 16) + "";
//            if(cmd.length()==1){
//                cmd = StringUtil.leftPad(cmd, 2,'0');
//            }
        }
        if(dto.getStartPrefix().equals("444e59")){
            cmd = dto.getCmd();
        }
        String classKey = ZDEventTagEnum.getValueByKey(cmd);
        IZDListenerService service = this.strategyMap.get(classKey);
        if (service != null) {
            log.info("开始调用相关监听类：" + service.getClass());
            service.doExecute(dto, client);
        } else {
            log.error("找不到相关类：" + classKey + "| 命令CMD：" + cmd);
        }
    }

//    public static void main(String[] args) {
//        String cmd = "2D01";
//        if (cmd.length() == 4) {
//            String orgCmd = CommonUtil.removeZero(reverseHex(cmd), true);
//            cmd = Integer.parseInt(orgCmd, 16) + "";
//        } else {
//            cmd = StringUtil.leftPad(cmd, 2);
//        }
//        System.out.println(cmd);
//    }
}
